package com.sylingd.blog.activity

import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.sylingd.blog.R
import com.sylingd.blog.bean.Meta
import com.sylingd.blog.lib.Api
import com.sylingd.blog.ui.index.ListFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
	private val mFragments = ArrayList<ListFragment>()
	private val metas = ArrayList<Meta>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

		setContentView(R.layout.activity_main)
		val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        this.title = getString(R.string.blog_title)

        val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)

		//首页
		metas.add(Meta(-1, getString(R.string.index), 0, 0))
		nav_view.menu.add(R.id.nav_meta, 0, 0, getString(R.string.index))
		mFragments.add(ListFragment.create(ListFragment.ALL_ID))

		loadMeta()

		load(0)
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
		if (item.itemId == R.id.launchSetting) {
			SettingActivity.launch(this)
		} else if (item.order <= metas.size) {
			load(item.order)
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }

    private fun loadMeta() {
		val req = Api.ApiRequest("index/meta")
		Api.call(req, object: Api.Callback() {
			override fun onSuccess(data: JsonElement) {
				nav_view.post({
					val gson = Gson()
					data.asJsonArray.forEach {
						val item = gson.fromJson(it, Meta::class.java)
						metas.add(item)
						val index = metas.size - 1
						nav_view.menu.add(R.id.nav_meta, index, index, item.title)
						mFragments.add(ListFragment.create(item.id))
					}
					nav_view.setNavigationItemSelectedListener(this@MainActivity)
				})
			}
		})
	}

    private fun load(id: Int) {
        val fm = this.fragmentManager
        val t = fm.beginTransaction()
        t.replace(R.id.mainFrame, mFragments[id])
        t.commit()
    }

}
